package cn.topcodes.tcsf.admin.web.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.util.List;

/**
 * @author Unicorn
 * @date 2017/5/15
 */


public class AdminSessionEndPoint extends TextWebSocketHandler {

    public static final String USER_ID = "userId";

    private static Logger logger = LoggerFactory.getLogger(AdminSessionEndPoint.class);

    @Autowired
    private WebSocketSessionCache sessionCache;

    public void broadcast(String text) {
        List<String> keys = sessionCache.getAll();
        for(String key : keys) {
            sendText(key, text);
        }
    }

    /**
     * 发送消息
     * @param userId
     * @param text
     */
    public void sendText(Long userId, String text) {
        sendText(userId + "", text);
    }

    public void sendText(String userId, String text) {
        WebSocketSession session = this.sessionCache.getAdminSession(userId);
        if(session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(text));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            throw new IllegalArgumentException("websocket推送失败，userId:" + userId + "会话失效");
        }
    }

    /**
     * 连接建立后
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        Object obj = session.getAttributes().get(USER_ID);
        if(obj != null) {
            sessionCache.addAdminSession(obj.toString(), session);
        }
        super.afterConnectionEstablished(session);
    }

    /**
     * 连接关闭后
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Object obj = session.getAttributes().get(USER_ID);
        if(obj != null) {
            sessionCache.removeAdminSessoin(obj.toString());
        }
        super.afterConnectionClosed(session, status);
    }

    /**
     * 处理文本消息
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session,
                                     TextMessage message) throws Exception {

//        System.out.println(message.getPayload());
        super.handleTextMessage(session, message);
//        TextMessage returnMessage = new TextMessage(message.getPayload()+" received at server");
//        session.sendMessage(returnMessage);
    }
}